<template>
  <div>
    <my-header></my-header>

    <el-card class="card">
      <!-- 提示区域：alert组件，:closable="false"移除原有的关闭叉叉按钮 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 进度条 -->
      <!-- 这里activeIndex-0是因为后面Tab绑定了activeIndex对象，输入的是字符串，减0后会将其强制转换为数字类型。 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="进基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- :before-leave  
 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
        <el-tabs
          v-model="activeIndex"
          :before-leave="beforeLeave"
          :tab-position="tabPosition"
          @tab-click="tabClicked"
        >
          <!-- name	与选项卡绑定值 value 对应的标识符，表示选项卡别名	string	—	该选项卡在选项卡列表中的顺序值，如第一个选项卡则为'1' -->
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)" prop="goods_price">
              <el-input v-model="ruleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="ruleForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="ruleForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="list"
                @change="handleChange"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <!-- 渲染表单的Item项 -->
            <!-- 父级 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <!-- 子级 -->
              <el-checkbox-group v-model="item.newValue">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <!-- 子级 -->
              <el-checkbox-group v-model="item.newValue">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <!-- el-upload商品图片上传
  action:指定图片上传api接口
  :on-preview ： 当点击图片时会触发该事件进行预览操作,处理图片预览
  :on-remove : 当用户点击图片右上角的X号时触发执行
  :on-success：当用户点击上传图片并成功上传时触发
  list-type ：设置预览图片的方式
  :headers ：设置上传图片的请求头 -->
            <el-upload
              :action="pathUrl"
              :headers="headerToken"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="successImage"
              list-type="picture"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="ruleForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="handlePreview" />
      <!-- <img src="../../../assets/logo.png" alt=""> -->
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { addGoods } from "../../../api/goods";
import { getCate, getCateList } from "../../../api/cate";
import myHeader from "../../../components/myHeader.vue";
export default {
  components: {
    myHeader,
  },
  data() {
    return {
      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      previewPath: "", //预览路径
      previewVisible: false,
      // 上传图片请求头
      headerToken: { Authorization: localStorage.getItem("token") },
      // 上传图片的地址
      pathUrl: "https://lianghj.top:8888/api/private/v1/upload",
      // pathUrl:"http://127.0.0.1:8888/api/private/v1/upload",
      // 基本信息参数
      value: [],
      ruleForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        // 商品所属的分类数组
        goods_cat: this.value,
        // 图片的数组
        pics: [],
        // 商品的详情描述
        goods_introduce: "",
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: [],
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      // 进度条完成情况
      activeIndex: "0",
      // 标签页左侧显示
      tabPosition: "left",
      // 标签页左侧标题
      arr: [
        { id: 1, tabs: "基本信息" },
        { id: 2, tabs: "商品参数" },
        { id: 3, tabs: "商品属性" },
        { id: 4, tabs: "商品图片" },
        { id: 5, tabs: "商品内容" },
      ],
      list: [],
    };
  },
  computed: {
    ...mapState(["token"]),
  },
  created() {
    this.getCateAdd();
  },
  methods: {
    // 添加商品
    add() {
      this.$refs["ruleForm"].validate(async (valid) => {
        console.log(valid, "valid");
        //验证通过
        if (valid) {
          this.ruleForm.goods_cat = this.ruleForm.goods_cat.join(",");
          //对选择过的动态参数或静态属性进行处理,按照接口要求提交
          //动态参数
          this.manyTableData.forEach((item) => {
            // console.log(258,item.newValue);
            let onlyVal = {
              attr_id: item.attr_id,
              attr_value: item.newValue,
            };
            this.ruleForm.attrs.push(onlyVal);
          });
          //静态属性
          this.onlyTableData.forEach((item) => {
            // console.log(258,item.newValue);
            let onlyVal = {
              attr_id: item.attr_id,
              attr_value: item.newValue,
            };
            this.ruleForm.attrs.push(onlyVal);
          });

          let res = await addGoods(this.ruleForm);
          console.log(res, "resAdd");
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg);
            this.$router.push("/goods");
          }

          this.ruleForm.goods_cat = [];
        } else {
          this.$message.error("请填写必要的商品信息");
          return false;
        }
      });
    },
    // 商品参数接口调用
    async tabClicked() {
      let cateId = this.ruleForm.goods_cat[2];
      console.log("点击的第几个", this.activeIndex);
      console.log("id", cateId);

      if (this.activeIndex == 1) {
        let res = await getCateList({ cate_id: cateId, sel: "many" });
        console.log(res, "getCateList");
        //把数据字符串处理数组渲染
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",");
          //绑定老数据有问题-可以深拷贝
          item.newValue = JSON.parse(JSON.stringify(item.attr_vals));
        });
        this.manyTableData = res.data;
        console.log(this.manyTableData, "this.manyTableData");
      }
      if (this.activeIndex == 2) {
        let res = await getCateList({ cate_id: cateId, sel: "only" });
        //把数据字符串处理数组渲染
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",");
          //绑定老数据有问题-可以深拷贝
          item.newValue = JSON.parse(JSON.stringify(item.attr_vals));
        });
        this.onlyTableData = res.data;
      }
    },
    // 标签页离开时所触发的函数
    beforeLeave(activeName, oldActiveName) {
      console.log(activeName, oldActiveName, "activeName, oldActiveName");
      if (oldActiveName === "0" && this.ruleForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    async getCateAdd() {
      let res = await getCate({
        type: 3,
        pagenum: 1,
        pagesize: 5,
      });
      console.log(res, "resCate");
      if (res.meta.status == 200) {
        this.list = res.data.result;
      }
    },
    // 基本信息
    // 级联选择器发生改变时
    handleChange(value) {
      console.log(value);
      this.ruleForm.goods_cat = value;
    },

    // 上传图片
    handleRemove(file) {
      //根据已知删除数据中某个值  点击的a  已有数据[1,2,a,b]  arr.findIndex(item=>{查找某个值}) 返回索引  splice(index,1)
      console.log(file);
      let delPath = file.response.data.tmp_path;
      //  console.log(delPath,"delPath");
      let index = this.ruleForm.pics.findIndex((item) => {
        item.pic == delPath;
      });
      this.ruleForm.pics.splice(index, 1);
      console.log("删除后的数组中值", this.ruleForm.pics);
    },
    // 处理图片预览效果-1.从文件流里，拿到后台上传成功的那个正式地址

    handlePreview(file) {
      console.log(file, "file");
      console.log("点击的那个图片信息", file);
      let preURL = file.response.data.url; //服务器上的地址
      this.previewPath = preURL;
      this.previewVisible = true;
    },
    // 监听图片上传成功的事件-response[{pic:临时路径地址}]
    successImage(file) {
      //存储后端响应信息,删除时从数组里删除
      console.log(file, "file");
      let path = file.data.tmp_path;
      this.ruleForm.pics.push({ pic: path });
      console.log("删除前的值", this.ruleForm.pics);
    },
  },
};
</script>

<style scoped>
.card {
  margin-top: 20px;
  height: 100%;
}
.el-steps {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
  height: 100%;
}
.el-tab-pane {
  height: 100%;
  line-height: 150px;
}
.handlePreview {
  width: 100%;
}
/* //sass,less: 注意此处用/deep/进行样式穿透时,可能会报错，可用::v-deep */
::v-deep .ql-editor {
  min-height: 300px;
}
</style>